<script setup>
  import { onMounted, ref } from 'vue'
  import { getMessageListAPI, getMessageReadAllAPI } from '@/apis/message'

  // 任务列表数据
  const notifyList = ref([])
  // 下一页页码
  const nextPage = ref(1)
  // 每页包含数据条数
  const pageSize = ref(5)
  // 判断列表长度是否为空
  const isData = ref(false)
  //下拉自定义动画显示
  const isShow = ref(false)
  // 总条数
  const totalPages = ref('')
  const time = ref(null)
  onMounted(() => {
    getMessageList()
  })
  // 全部已读
  const getMessageReadAll = async () => {
    const res = await getMessageReadAllAPI(201)
    getMessageList()
  }
  // 获取消息列表
  const getMessageList = async () => {
    const { data, code } = await getMessageListAPI({
      contentType: 201,
      page: nextPage.value,
      pageSize: pageSize.value,
    })
    // console.log(data)
    if (code !== 200) return uni.utils.toast('获取消息列表失败')

    //渲染列表
    notifyList.value = [...notifyList.value, ...data.items]

    // 是否还有更多数据
    totalPages.value = +data.pages

    //是否为空列表
    isData.value = notifyList.value.length === 0
  }
  // 获取数据
  const refresherrefresh = async () => {
    isShow.value = true
    //更新页码
    // nextPage.value = 1
    // 清空原始的数据
    notifyList.value = []
    await getMessageList()
    isShow.value = false
  }
  //监听页面上拉刷新页码事件
  const scrollTolower = (e) => {
    // console.log(e.detail.direction)
    if (nextPage.value >= totalPages.value) return
    //更新下一页页码
    nextPage.value++
    // const time = setTimeout(() => {
    //   console.log('防抖')
    //   getMessageList()
    // }, 500)
    // if (e.detail.direction) {
    //   clearInterval(time)
    // }
    getMessageList()
  }
</script>
<template>
  <scroll-view
    @scrolltolower="scrollTolower"
    @refresherrefresh="refresherrefresh"
    :refresher-triggered="isShow"
    class="scroll-view"
    refresher-enabled
    scroll-y
  >
    <view class="scroll-view-wrapper">
      <view class="message-action" @click="getMessageReadAll">
        <text class="iconfont icon-clear"></text>
        全部已读
      </view>
      <uni-card
        v-for="item in notifyList"
        :key="item.id"
        :border="false"
        :is-shadow="false"
      >
        <view class="brief">{{ item.content }}</view>
        <view class="extra">
          <text class="time">{{ item.created }}</text>
          <navigator
            hover-class="none"
            class="link"
            url="`/subpkg_message/content/index?id=${item.id}`"
            >查看详情</navigator
          >
        </view>
        <template v-slot:title>
          <view :class="{ unread: !item.isRead }" class="title"
            >您有新的运输任务</view
          >
        </template>
      </uni-card>

      <view v-if="isData" class="message-blank">暂无消息</view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
